package com.yunban.project.template.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunban.project.template.mapper.PromptTemplateMapper;
import com.yunban.project.template.model.domain.PromptTemplate;
import com.yunban.project.template.service.PromptTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author: lijiajun
 * @date: 2025-03-03
 * @version: 1.0
 */
@Slf4j
@Service
public class PromptTemplateServiceImpl extends ServiceImpl<PromptTemplateMapper, PromptTemplate> implements PromptTemplateService {

    @Override
    public List<Tree<Long>> getPromptTemplateTree(List<Long> ids) {
        // 获取提示词列表
        LambdaQueryWrapper<PromptTemplate> queryWrapper = new LambdaQueryWrapper<>();
        if (!CollectionUtils.isEmpty(ids)) {
            queryWrapper.in(PromptTemplate::getId, ids);
        } else {
            queryWrapper.in(PromptTemplate::getId, List.of(-1));
        }
        // 先按 level 升序排 然后再按 sort 升序排
        queryWrapper.orderByAsc(PromptTemplate::getLevel, PromptTemplate::getSort);
        List<PromptTemplate> promptTemplateList = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(promptTemplateList)) {
            return new ArrayList<>();
        }
        // 将 提示词列表 转换成树形结构
        List<TreeNode<Long>> promptTemplateTreeNodes = promptTemplateList.stream().map(items -> {
            TreeNode<Long> node = new TreeNode<>();
            //下面四个属性是树型结构必有的属性
            node.setId(items.getId());
            node.setName(items.getValue());
            node.setParentId(items.getParentId());
            node.setWeight(items.getSort());
            // 以下为扩展属性（业务不一样属性也不一样）
            Map<String, Object> extra = new HashMap<>();
            extra.put("level", items.getLevel());
            extra.put("prompt", items.getPrompt());
            extra.put("hasDefault", items.isHasDefault());
            node.setExtra(extra);
            return node;
        }).toList();
        log.info("promptTemplateTreeNodes:{}", JSON.toJSONString(promptTemplateTreeNodes));
        return TreeUtil.build(promptTemplateTreeNodes, 0L);
    }
}
